package com.woniuxy.file.controller;

import com.aliyun.oss.OSSClient;
import com.woniuxy.commons.util.ResponseResult;
import com.woniuxy.file.entity.UploadResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    //springboot直接整合好的
    @Resource
    private OSSClient ossClient;
    private String bucketname = "springcloud-79-tangzhenfeng";
    private String baseUrl = "https://springcloud-79-tangzhenfeng.oss-cn-chengdu.aliyuncs.com/";

    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws Exception {
        System.out.println("文件名字"+file.getOriginalFilename());
        String filename = file.getOriginalFilename();
        //1获取文件流对象
        InputStream inputStream = file.getInputStream();
        String uuid = UUID.randomUUID().toString();
        String suf = filename.substring(filename.lastIndexOf("."));
        filename = uuid + suf;

        //2将流对象设置到ossClient
        ossClient.putObject(bucketname,filename,inputStream);

        //3设置文件过期时间:30天
        Date date = new Date(new Date().getTime()+1000*3600*24*30);
        //4上传阿里云
        URL url = ossClient.generatePresignedUrl(bucketname, filename, date);

        //5封装结果
        ResponseResult<UploadResult> result = new ResponseResult<>();
        result.setCode(200);
        result.setMessage("上传成功");
        result.setData(new UploadResult(filename,baseUrl+filename));

        return result;
    }
}
